package calculadora;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;


public class Tela extends JFrame implements ActionListener{

	private JTextField visor;
	ArrayList<JButton> botoes = new ArrayList<JButton>();
	JPanel panel;
	private boolean escrito = false;
	private boolean operacao = false;
	private boolean calculou = false;
	String[] stringBotoes = {"←", "C", "±", "√", "x²", "7", "8", "9", "/", "x³", "4", "5", "6", "*", "1/x",
			"1", "2", "3", "-", "=", "0", ",", "+" };

	private boolean clicouSinal = false;
	private double num1, num2;
	private String sinal;
	public Tela() {

		super("Calculadora");
		setLayout(new GridBagLayout());
		setLocationRelativeTo(null);
		setSize(260,255);
		setIconImage(new ImageIcon(getClass().getResource("icone.png")).getImage());
		visor = new JTextField("0");
		visor.setBackground(Color.WHITE);;
		visor.setEditable(false);
		visor.setFont(new Font("Consolas", Font.PLAIN, 28));
		visor.setHorizontalAlignment(JTextField.RIGHT);

		GridBagConstraints c = new GridBagConstraints();
		for(int i=0; i < stringBotoes.length; i++){
			botoes.add(new JButton());
			botoes.get(i).setText(stringBotoes[i]);
			if(stringBotoes[i].equals("="))
				botoes.get(i).setFont(new Font("Consolas", Font.BOLD, 25));
			else
				botoes.get(i).setFont(new Font("Consolas", Font.PLAIN, 16));
			if((stringBotoes[i].length() < 2) && Character.isDigit(stringBotoes[i].charAt(0)) || stringBotoes[i].equals(","))
				botoes.get(i).setBackground(new Color(239, 244, 249));
			else 
				botoes.get(i).setBackground(new Color(213, 224, 237));
		}

		int x = 0;
		int y = 1;
		c.weightx=0.5;

		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 5;
		visor.setColumns(16);
		add(visor, c);
		for(int i = 0; i < botoes.size(); i++) {

			c.gridx = x;
			c.gridy = y;
			c.insets = new Insets(6, 2, 0, 2);
			c.fill = GridBagConstraints.BOTH;
			if(stringBotoes[i].equals("0")) {
				c.gridwidth = 2;
				x++;
			} else if(stringBotoes[i].equals("=")) {
				c.gridheight = 2;
			} else {
				c.gridwidth = 1;
				c.gridheight = 1;
			}
			add(botoes.get(i), c);

			x++;
			if(x == 5) {
				x = 0;
				y++;
			}
		}

		for (int i = 0; i < botoes.size(); i++) {
			botoes.get(i).addActionListener(this);
		}




		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
	}


	public void actionPerformed(ActionEvent e) {

		for (int i = 0; i < botoes.size(); i++) {
			if(e.getSource() == botoes.get(i))
				this.botaoClicado(botoes.get(i).getText());
		}
	}

	private void botaoClicado(String txtBtn) {
		if( txtBtn.length() < 2 && Character.isDigit(txtBtn.charAt(0)) ) {
			for(int i=0; i<=9; i++)
			{
				if(txtBtn.equals(i+"")){
					escreverNumero(txtBtn);
				}
			}
		}
		else if(txtBtn.equals("1/x")) {
			umSobreX();
		}
		else if(txtBtn.equals("←")){
			apagar();
		} else if(txtBtn.equals("C")) {
			limparMemoria();
		} else if(txtBtn.equals(",")) {
			escreverVirgula();
		} else if(txtBtn.equals("±")) {
			modificarSinal();
		} else if(txtBtn.equals("x²")) {
			potencia(2);
		} else if(txtBtn.equals("x³")) {
			potencia(3);
		} else if(txtBtn.equals("√")) {
			raiz();
		} else if(txtBtn.equals("=")) {
			igual();
		}else  {
			operacao(txtBtn);
		} 
	}

	private void limparMemoria() {
		num1 = 0;
		num2 = 0;
		visor.setText("0");
		this.calculou = false;
		this.escrito = false;
		this.clicouSinal = false;
	}

	private void igual() {
		if(!this.calculou && clicouSinal) {
			this.num2 = Double.parseDouble(visor.getText().replace(',' , '.'));
			double resultado = calcular();
			this.visor.setText(String.format("%.2f", resultado));
			this.clicouSinal = true;
			this.calculou = true;
			this.escrito = false;
			this.num1=resultado;
			this.num2=0;
		}
	}

	public void operacao(String sinal) {
		this.sinal = sinal;

		if(!clicouSinal) {
			this.num1 = Double.parseDouble(visor.getText().replace(',' , '.'));
			escrito=false;
			clicouSinal = true;
		} else {
			igual();
			
		}
	}

	private double calcular() {
		if(this.sinal.equals("+"))
			return this.num1 + this.num2;
		else if(this.sinal.equals("-")) {
			return this.num1 - this.num2;
		} else if(this.sinal.equals("*"))
			return this.num1 * this.num2;
		else  {
			if (num2 == 0){
				this.visor.setText("Indeterminado");
			} else {
				return this.num1/this.num2;
			}
			
		}
		this.escrito=false;
		return 0;
	}

	private void raiz() {
		if(this.escrito || this.calculou) {
			double val = Double.parseDouble(visor.getText().replace(',' ,'.'));
			double resultado = Math.sqrt(val);

			this.visor.setText(String.format("%.2f", resultado));
			this.operacao = true;
		}
	}

	private void umSobreX() {
		if(this.escrito || this.visor.getText().equals("0") || this.calculou) {
			double val = Double.parseDouble(visor.getText().replace(',' ,'.'));
			double resultado;
			if(val != 0){
				resultado = 1/val;
				this.visor.setText(String.format("%.2f", resultado));
			} else{
				this.visor.setText("Indeterminado");
				this.escrito=false;
			}

			this.operacao = true;
		}
	}

	private void potencia(int n) {
		if(this.escrito || this.calculou) {
			double val = Double.parseDouble(visor.getText().replace(',' ,'.'));
			double resultado = Math.pow(val, n);

			this.visor.setText(String.format("%.2f", resultado));
			this.operacao = true;
		}
	}

	private void modificarSinal() {
		String aux = this.visor.getText();
		if(aux.contains("-")) {
			aux = aux.substring(1);
		} else if(escrito || this.calculou){
			aux = "-" + aux;
		}

		visor.setText(aux);

	}

	private void escreverVirgula() {
		String aux = this.visor.getText();
		if(!aux.contains(",")) {
			aux+=",";
			visor.setText(aux);
			this.escrito = true;
		} 
	}

	private void apagar() {
		if(this.escrito || this.calculou) {
			String aux = this.visor.getText();
			aux = aux.substring(0, aux.length()-1);

			if(aux.isEmpty() || aux.equals("0")) {
				this.visor.setText("0");
				this.escrito=false;
			} else {
				visor.setText(aux);
			}
		} else {
			this.visor.setText("0");
		}
	}

	public void escreverNumero(String n){
		this.calculou = false;
		if(!n.equals("0")){

			if(!this.escrito || this.operacao) {
				this.visor.setText(n);
				this.escrito = true;
				this.operacao = false;
			}	
			else {
				this.visor.setText(this.visor.getText()+ n);
				this.escrito = true;
			}
		} else {
			if(this.escrito){
				this.visor.setText(this.visor.getText()+ n);
			} else if(this.clicouSinal) {
				this.visor.setText(n);
				this.escrito = true;
				this.operacao = false;
			}
		}
	}
}